# -*- coding: UTF-8 -*-
import csv
import os
import time


base_dir = os.path.dirname(os.path.dirname(__file__))
data_path = os.path.join(base_dir, 'config')
path = os.path.join(data_path, 'temporary.csv')
path_other = os.path.join(data_path, 'other_path_db.csv')


def write_csv_person_info(info, fieldnames=None, csv_file=path, is_have_header=False):
    """
    info : 传入值--》dict
    csv_file : 文件位置
    fieldnames : 列表头，需要和info的key一致
    is_have_header : 默认不写入头
    """
    with open(csv_file, 'a+', newline='') as f:
        writer = csv.DictWriter(f, fieldnames)
        if is_have_header:
            writer.writeheader()
        writer.writerow(info)
        time.sleep(1)


def read_csv_person_info(csv_file):
    all_list = []
    with open(csv_file)as f:
        f_csv = csv.reader(f)
        for row in f_csv:
            all_list.append({row[0]: [v for v in row if v != row[0]]})
    return all_list


# 清空数据
def clear_csv_info(csv_file):
    try:
        file = open(csv_file, "r+")
        file.truncate()
    except Exception as e:
        return e


def find_csv_key(key):
    """
    通过关键字查找指定的域名
    """
    for red in read_csv_person_info(csv_file=path_other):
        if key in red.keys():
            return red[key]


if __name__ == '__main__':
    print(find_csv_key('clickhouse'))
